package com.lizard.schedule.ui.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.VolleyError;
import com.lizard.schedule.manager.AccountManager;
import com.lizard.schedule.manager.umeng.UmengLoginManager;
import com.lizard.schedule.net.http.request.HttpRequestManager;
import com.lizard.schedule.net.http.consts.ReturnCode;
import com.lizard.schedule.net.http.request.HttpResponseListener;
import com.lizard.schedule.net.http.request.bean.LoginRequest;
import com.lizard.schedule.net.http.request.bean.ThirdLoginRequest;
import com.lizard.schedule.net.http.response.bean.LoginResponse;
import com.lizard.schedule.R;
import com.lizard.schedule.net.http.response.bean.ThirdLoginResponse;
import com.lizard.schedule.ui.activity.base.BaseActivity;
import com.lizard.schedule.utils.DeviceUtil;
import com.lizard.schedule.utils.ToastUtil;
import com.lizard.schedule.widget.ScheduleProgressDialog;
import com.lizard.schedule.widget.ScheduleToast;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;

/**
 * 登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener{

    private final int REQUEST_CODE_REGISTER = 0;

    /**
     * “直接使用”按钮
     */
    private Button directUseBtn;

    /**
     * 用户名输入
     */
    private EditText usernameInput;

    /**
     * 密码输入
     */
    private EditText pwdInput;

    /**
     * “登录”按钮
     */
    private Button loginBtn;

    /**
     * “注册”按钮
     */
    private Button registBtn;

    /**
     * 其他方式登录
     */
    private View otherLoginBtn;

    private View loginV1;

    private View loginV2;

    /**
     * 是否正在动画
     */
    private boolean doingAnim = false;

    /**
     * "微博登录"按钮
     */
    private View weiboLoginBtn;

    /**
     * "QQ登录"按钮
     */
    private View qqLoginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_login);

        initView();

        setViewClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * view初始化
     */
    private void initView(){
        directUseBtn = (Button)findViewById(R.id.direct_use_btn);
        usernameInput = (EditText) findViewById(R.id.username_input);
        pwdInput = (EditText) findViewById(R.id.pwd_input);
        pwdInput.setTypeface(Typeface.DEFAULT);
        pwdInput.setTransformationMethod(new PasswordTransformationMethod());
        loginBtn = (Button) findViewById(R.id.login_btn);
        registBtn = (Button) findViewById(R.id.regist_btn);
        otherLoginBtn = findViewById(R.id.other_login_btn);
        loginV1 = findViewById(R.id.login_v1);
        loginV1.setVisibility(View.VISIBLE);
        loginV2 = findViewById(R.id.login_v2);
        loginV2.setVisibility(View.VISIBLE);
        loginV2.setTranslationX(DeviceUtil.getScreenWidth());
        weiboLoginBtn = findViewById(R.id.weibo_login_btn);
        qqLoginBtn = findViewById(R.id.qq_login_btn);
    }

    /**
     * view点击事件设置
     */
    private void setViewClick(){
        directUseBtn.setOnClickListener(this);
        loginBtn.setOnClickListener(this);
        registBtn.setOnClickListener(this);
        otherLoginBtn.setOnClickListener(this);
        weiboLoginBtn.setOnClickListener(this);
        qqLoginBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if(view == directUseBtn){
            directUse();
        } else if(view == loginBtn){
            login();
        } else if(view == registBtn){
            register();
        } else if(view == otherLoginBtn){
            switchLoginView();
        } else if(view == weiboLoginBtn){
            weiboLogin();
        } else if(view == qqLoginBtn){
            qqLogin();
        }
    }

    /**
     * 微博登录
     */
    private void weiboLogin(){
        UmengLoginManager.getInstance().doSinaSsoLogin(this, new SocializeListeners.UMAuthListener() {
            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
                ToastUtil.showScheduleToastS(R.string.authorise_failed);
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {

                if(value != null){
                    final String uid = value.getString("uid");
                    final String accessToken = value.getString("access_token");

                    if(!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(accessToken)){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                thirdLogin(ThirdLoginRequest.TYPE_WEIBO, uid, accessToken);
                            }
                        });
                    } else{
                        ToastUtil.showScheduleToastS(R.string.authorise_failed);

                    }
                } else{
                    ToastUtil.showScheduleToastS(R.string.authorise_failed);
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
            }

            @Override
            public void onStart(SHARE_MEDIA platform) {
            }
        });
    }

    /**
     * QQ登录
     */
    private void qqLogin(){
        UmengLoginManager.getInstance().doQqSsoLogin(this, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
                ToastUtil.showScheduleToastS(R.string.authorise_failed);
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {

                if(value != null){

                    final String uid = value.getString("uid");
                    final String accessToken = value.getString("access_token");

                    if(!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(accessToken)){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                thirdLogin(ThirdLoginRequest.TYPE_QQ, uid, accessToken);
                            }
                        });
                    } else{
                        ToastUtil.showScheduleToastS(R.string.authorise_failed);

                    }
                } else{
                    ToastUtil.showScheduleToastS(R.string.authorise_failed);
                }

            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
            }
        });
    }

    private void thirdLogin(final int type, String uid, String accessToken){
        final ScheduleProgressDialog.Builder progressDialogBuilder = new ScheduleProgressDialog.Builder(this)
                .setText(R.string.login_progress_hint)
                .setCancelable(false);
        progressDialogBuilder.show();
        final ThirdLoginRequest request = new ThirdLoginRequest();
        request.setUid(uid);
        request.setType(type);
        request.setAccessToken(accessToken);
        HttpRequestManager.getInstance().request(request, new HttpResponseListener<ThirdLoginResponse>() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                progressDialogBuilder.cancel();
                ScheduleToast.makeScheduleToastS(R.string.network_error).show();
            }

            @Override
            public void onResponse(ThirdLoginResponse response) {
                progressDialogBuilder.cancel();
                if (ReturnCode.SUCCESS.equals(response.getReturnCode())) {    // 成功

                    String username = response.getUsername();
                    String pwd = response.getPwd();
                    String token = response.getToken();

                    if(!TextUtils.isEmpty(username) && ! TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(token)){
                        AccountManager.getInstance().loginInit(username, pwd, token, type);
                        startActivity(new Intent(LoginActivity.this, MainPageActivity.class));
                        finish();
                    } else{
                        ScheduleToast.makeScheduleToastS(R.string.login_failed).show();
                    }

                } else {    // 失败
                    ScheduleToast.makeScheduleToastS(R.string.login_failed).show();
                }
            }
        });
    }

    /**
     * 提交登录信息到server
     *
     * @param username
     * @param pwd
     */
    private void submitLogin(final String username, final String pwd){
        final ScheduleProgressDialog.Builder progressDialogBuilder = new ScheduleProgressDialog.Builder(this)
                .setText(R.string.login_progress_hint)
                .setCancelable(false);
        progressDialogBuilder.show();
        final LoginRequest request = new LoginRequest();
        request.setUsername(username);
        request.setPassword(pwd);
        HttpRequestManager.getInstance().request(request, new HttpResponseListener<LoginResponse>() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                progressDialogBuilder.cancel();
                ScheduleToast.makeScheduleToastS(R.string.network_error).show();
            }

            @Override
            public void onResponse(LoginResponse response) {
                progressDialogBuilder.cancel();
                if (ReturnCode.SUCCESS.equals(response.getReturnCode())) {    // 成功
                    String token = response.getToken();
                    if(!TextUtils.isEmpty(token)){
                        AccountManager.getInstance().loginInit(username, pwd, token, 0);
                        startActivity(new Intent(LoginActivity.this, MainPageActivity.class));
                        finish();
                    } else{
                        ScheduleToast.makeScheduleToastS(R.string.login_failed).show();
                    }
                } else if (ReturnCode.USER_NOT_EXIST.equals(response.getReturnCode())) { // 用户不存在
                    ScheduleToast.makeScheduleToastS(R.string.login_user_not_exist).show();
                } else if (ReturnCode.USER_FORBIDDEN.equals(response.getReturnCode())) { // 用户已禁用
                    ScheduleToast.makeScheduleToastS(R.string.account_fobidden).show();
                } else if (ReturnCode.USERNAME_OR_PWD_ERROR.equals(response.getReturnCode())) { // 用户名或密码错误
                    ScheduleToast.makeScheduleToastS(R.string.username_or_pwd_error).show();
                } else {    // 失败
                    ScheduleToast.makeScheduleToastS(R.string.login_failed).show();
                }
            }
        });
    }

    /**
     * 动画切换登录方式
     */
    private void switchLoginView(){

        if(doingAnim){
            return;
        }

        if(loginV1.getTranslationX() >= 0){ // 切换到V2
            ObjectAnimator anim = ObjectAnimator.ofFloat(loginV2, "translationX", DeviceUtil.getScreenWidth(), 0).setDuration(200);
            anim.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animator) {
                    doingAnim = true;
                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    doingAnim = false;
                }

                @Override
                public void onAnimationCancel(Animator animator) {
                    doingAnim = false;
                }

                @Override
                public void onAnimationRepeat(Animator animator) {

                }
            });
            anim.start();

            ObjectAnimator anim2 = ObjectAnimator.ofFloat(loginV1, "translationX", 0, -DeviceUtil.getScreenWidth()).setDuration(200);
            anim2.start();

        } else { // 切换到V1
            ObjectAnimator anim = ObjectAnimator.ofFloat(loginV1, "translationX", -DeviceUtil.getScreenWidth(), 0).setDuration(200);
            anim.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animator) {
                    doingAnim = true;
                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    doingAnim = false;
                }

                @Override
                public void onAnimationCancel(Animator animator) {
                    doingAnim = false;
                }

                @Override
                public void onAnimationRepeat(Animator animator) {

                }
            });
            anim.start();

            ObjectAnimator anim2 = ObjectAnimator.ofFloat(loginV2, "translationX", 0, DeviceUtil.getScreenWidth()).setDuration(200);
            anim2.start();

        }
    }

    /**
     * 登录
     */
    private void login(){
        String username = usernameInput.getText().toString().trim();
        String pwd = pwdInput.getText().toString().trim();

        if(TextUtils.isEmpty(username)){
            usernameInput.setError(getString(R.string.please_input_username));
            return;
        }

        if(TextUtils.isEmpty(pwd)){
            pwdInput.setError(getString(R.string.please_input_pwd));
            return;
        }

        // 提交登录信息到server
        submitLogin(username, pwd);
    }

    /**
     * 注册
     */
    private void register(){
        startActivityForResult(new Intent(this, RegisterActivity.class), REQUEST_CODE_REGISTER);
    }

    /**
     * 直接使用
     */
    private void directUse(){
        AccountManager.getInstance().loginInit(null, null, null, 0);
        startActivity(new Intent(LoginActivity.this, MainPageActivity.class));
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode == REQUEST_CODE_REGISTER){
                String username = data.getStringExtra("username");
                String pwd = data.getStringExtra("pwd");
                usernameInput.setText(username);
                pwdInput.setText(pwd);
            }
        }

        UmengLoginManager.getInstance().doSinaOnActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void finishForLogout(){
        // do nothing
    }
}
